//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//********************************************************* 

using System.Text;

namespace Microsoft.TridentWordAddIn.Presentation
{
    using System.IO;
    using System.Security.Cryptography;

    /// <summary>
    /// Class to calculate hasd CRC32 for stream
    /// </summary>
    public class Crc32 : HashAlgorithm
    {
        private const uint DefaultPolynomial = 0xedb88320;
        private const uint DefaultSeed = 0xffffffff;
        private uint hash;
        private uint seed;
        private uint[] table;

        /// <summary>
        /// Initializes a new instance of the <see cref="Crc32"/> class.
        /// </summary>
        public Crc32()
        {
            this.table = InitializeTable(DefaultPolynomial);
            this.seed = DefaultSeed;
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Crc32"/> class.
        /// </summary>
        /// <param name="polynomial">The polynomial.</param>
        /// <param name="seed">The seed.</param>
        public Crc32(uint polynomial, uint seed)
        {
            this.table = InitializeTable(polynomial);
            this.seed = seed;
            this.Initialize();
        }

        /// <summary>
        /// Gets the size, in bits, of the computed hash code.
        /// </summary>
        /// <value></value>
        /// <returns>The size, in bits, of the computed hash code.</returns>
        public override int HashSize
        {
            get { return 32; }
        }

        /// <summary>
        /// Computes the specified polynomial.
        /// </summary>
        /// <param name="polynomial">The polynomial.</param>
        /// <param name="seed">The seed.</param>
        /// <param name="buffer">The buffer.</param>
        /// <returns>UInt32</returns>
        public static uint Compute(uint polynomial, uint seed, byte[] buffer)
        {
            return CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
        }

        /// <summary>
        /// Gets the hash string.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <returns>string</returns>
        public static string GetHashString(Stream inputStream)
        {
            inputStream.Position = 0;
            Crc32 crc32 = new Crc32();
            StringBuilder hashString = new StringBuilder();

            foreach (byte b in crc32.ComputeHash(inputStream))
            {
                hashString.Append(b.ToString("x2").ToLower());
            }

            return hashString.ToString();
        }

        /// <summary>
        /// Initializes an implementation of the <see cref="T:System.Security.Cryptography.HashAlgorithm"/> class.
        /// </summary>
        public override void Initialize()
        {
            this.hash = this.seed;
        }

        /// <summary>
        /// Hashes the core.
        /// </summary>
        /// <param name="array">The input to compute the hash code for.</param>
        /// <param name="start">The start.</param>
        /// <param name="size">The size.</param>
        protected override void HashCore(byte[] array, int start, int size)
        {
            this.hash = CalculateHash(this.table, this.hash, array, start, size);
        }

        /// <summary>
        /// When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic stream object.
        /// </summary>
        /// <returns>The computed hash code.</returns>
        protected override byte[] HashFinal()
        {
            byte[] hashBuffer = UInt32ToBigEndianBytes(this.hash);
            this.HashValue = hashBuffer;
            return hashBuffer;
        }

        /// <summary>
        /// Initializes the table.
        /// </summary>
        /// <param name="polynomial">The polynomial.</param>
        /// <returns>UInt32[]</returns>
        private static uint[] InitializeTable(uint polynomial)
        {
            uint[] createTable = new uint[256];
            for (int i = 0; i < 256; i++)
            {
                uint entry = (uint)i;
                for (int j = 0; j < 8; j++)
                {
                    if ((entry & 1) == 1)
                    {
                        entry = (entry >> 1) ^ polynomial;
                    }
                    else
                    {
                        entry = entry >> 1;
                    }
                }

                createTable[i] = entry;
            }

            return createTable;
        }

        /// <summary>
        /// Calculates the hash.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <param name="seed">The seed.</param>
        /// <param name="buffer">The buffer.</param>
        /// <param name="start">The start.</param>
        /// <param name="size">The size.</param>
        /// <returns>UInt32</returns>
        private static uint CalculateHash(uint[] table, uint seed, byte[] buffer, int start, int size)
        {
            uint crc = seed;
            for (int i = start; i < size; i++)
            {
                unchecked
                {
                    crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
                }
            }

            return ~crc;
        }

        /// <summary>
        /// Us the int32 to big endian bytes.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <returns>byte[]</returns>
        private static byte[] UInt32ToBigEndianBytes(uint x)
        {
            return new byte[] {
			(byte)((x >> 24) & 0xff),
			(byte)((x >> 16) & 0xff),
			(byte)((x >> 8) & 0xff),
			(byte)(x & 0xff)
		     };
        }
    }
}
